from django.shortcuts import render, redirect,HttpResponse
from utils.sql_helper import exec_sql


def classes(request):
    class_list = exec_sql("select id, cname from class", is_get_list=True)
    return render(request, "class/classes.html", {"class_list": class_list})


def add_class(request):
    if request.method == "POST":
        cname = request.POST.get("cname")
        exec_sql(f'insert into class (cname) values ("{cname}")',is_modify=True)
        return redirect("/classes/")
    return render(request, "class/add_class.html")


def del_class(request):
    cid = request.GET.get("cid")
    exec_sql(f"delete from class where id = {cid}", is_modify=True)
    return redirect("/classes/")


def edit_class(request):
    if request.method == "POST":
        cid = request.POST.get("cid")
        cname = request.POST.get("cname")
        exec_sql(f'update class set cname = "{cname}" where id = {cid}', is_modify=True)
        return redirect("/classes/")
    cid = request.GET.get("cid")
    class_obj = exec_sql(f'select id, cname from class where id= {cid}', is_get_one=True)
    return render(request, "class/edit_class.html", {"class_one":class_obj})